package com.xuecheng.gateway.filter;

import cn.hutool.core.net.URLDecoder;
import cn.hutool.core.net.URLEncodeUtil;
import com.alibaba.fastjson.JSON;
import com.xuecheng.commons.constants.UserConstants;
import com.xuecheng.commons.model.vo.AuthInfo;
import com.xuecheng.commons.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.concurrent.TimeUnit;

/**
 * @author HuangYuwu
 * @CreateTime 2022/9/11 10:21
 */
@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取request和response
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        // 2.放行一部分url
        // 2-1 获取客户端请求url地址
        String path = request.getURI().getPath();
        // 2-2 判断部分地址放行
        if (path.contains("coursePub/preview") ||
                path.contains("auth/login") ||
                path.contains("basic/dictionary") ||
                path.contains("category/tree-nodes") ||
                path.contains("course/upload") ||
                path.contains("search/") ||
                path.contains("payment/wx/notify")) {
            return chain.filter(exchange);
        }
        // 3.获取请求头token
        String token = request.getHeaders().getFirst("Authorization");
        // 4.校验token合法性
        Boolean verifyToken = JwtUtils.verifyToken(token);
        if (!verifyToken) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 5.提取用户信息
        AuthInfo authInfo = JwtUtils.getInfoFromToken(token);
        // 6.校验token是否过期
        if (!redisTemplate.hasKey(UserConstants.USER_ID + authInfo.getUid())) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // 7.续期
        Long expire = redisTemplate.getExpire(UserConstants.USER_ID + authInfo.getUid());
        if (expire < 30) {
            redisTemplate.expire(UserConstants.USER_ID + authInfo.getUid(), 180, TimeUnit.MINUTES);
        }

        String encode;
        try {
            encode = URLEncoder.encode(JSON.toJSONString(authInfo), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        // 8.将用户信息设置到request头
        ServerHttpRequest serverHttpRequest = request.mutate().header("payload", encode).build();

        // 8-1 将新的request设置到exchange
        exchange.mutate().request(serverHttpRequest);
        // 9.放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
